import {LogoutOutlined, SettingOutlined} from '@ant-design/icons';
import {Avatar, Button, Form, Input, Menu, message, Modal, Spin} from 'antd';
import React from 'react';
import {connect} from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import {logout} from "@/services/login";
import avatar from '@/assets/img/avatar.png'
import {updatePassword} from "@/services/user";

class AvatarDropdown extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUserInfo: JSON.parse(sessionStorage.getItem('user')),
      visible: false
    }
  }


  onMenuClick = (event) => {
    const {key} = event;

    if (key === 'logout') {
      const {dispatch} = this.props;

      sessionStorage.clear();
      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }
      message.success("退出成功")
      return;
    }
    this.setState({
      visible: true
    })
    //history.push(`/account/${key}`);
  };

  componentDidMount() {

  }

  submit() {

  }

  onFinish = (v)=> {
    if (v.newPassword !== v.confirmPassword) {
      message.error('两次输入密码不一致')
      return
    }
    updatePassword(v).then(res=>{
      if (res && res.status === '0') {
        message.success('密码修改成功')
        this.setState({
          visible: false
        })
        //history.push(`/`);
      }else {
        message.error(res.message)
      }
    })
  }

  onFinishFailed(e) {
    //console.log((e)
  }

  // passwordValidator = (rule, value, callback) => {
  //   let userPwd = value
  //
  //   if (userPwd == undefined) {
  //     return true
  //   }
  //   if (!(userPwd != '' && (userPwd.length >= 8 && userPwd.length <= 20))) {
  //     callback('输入的密码格式错误，长度为8-20')
  //   }
  //   callback()
  // }

  render() {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const {currentUserInfo, visible} = this.state;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {/*{menu && (*/}
        {/*  <Menu.Item key="center">*/}
        {/*    <UserOutlined />*/}
        {/*    个人中心*/}
        {/*  </Menu.Item>*/}
        {/*)}*/}
        {menu && (
          <Menu.Item key="settings">
            <SettingOutlined/>
            修改密码
          </Menu.Item>
        )}
        {menu && <Menu.Divider/>}

        <Menu.Item key="logout">
          <LogoutOutlined/>
          退出登录
        </Menu.Item>
      </Menu>
    );
    const layout = {
      labelCol: {span: 4},
      wrapperCol: {span: 20},
    };
    const tailLayout = {
      wrapperCol: { offset: 4, span: 20 },
    };
    return currentUserInfo ? (
      <>
        <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={avatar} alt="avatar"/>
          <span className={`${styles.name} anticon`}>{currentUserInfo.userName}</span>
        </span>
        </HeaderDropdown>
        <Modal title="修改密码" footer={null} visible={visible} onOk={() => this.submit()} onCancel={() => {
          this.setState({
            visible: false
          })
        }}>
          <Form
            name="basic"
            {...layout}
            onFinish={(values)=>this.onFinish(values)}
            onFinishFailed={(err)=>this.onFinishFailed(err)}
          >

            <Form.Item
              label="原密码"
              name="oldPassword"
              rules={[
                {required: true, message: '请输入原密码!'},
                {max: 32, message: '最大长度是32位'},
              ]}
            >
              <Input.Password/>
            </Form.Item>
            <Form.Item
              label="新密码"
              name="newPassword"
              rules={[
                {required: true, message: '请输入新密码!'},
                {max: 32, message: '最大长度是32位'},
              ]}
            >
              <Input.Password/>
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="confirmPassword"
              rules={[
                {required: true, message: '请输入确认密码!'},
                {max: 32, message: '最大长度是32位'},
              ]}
            >
              <Input.Password/>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button htmlType="button" style={{ margin: '0 8px' }} onClick={()=>{
                this.setState({
                  visible: false
                })
              }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
